const std = @import("std");

const Food = @import("../map/food.zig");
const Cell = @import("../cell.zig");

const MaxFoodSize: u8 = 6;

const Stomach = @This();

cell: *Cell,

list: std.ArrayList(*Food),
size: u8,
speed: f32,
energy_efficiency: f32 = 1.0, // 每秒能吸收的能量

pub fn init(cell: *Cell) @This() {
    return .{
        .cell = cell,
        .list = std.ArrayList(*Food).init(cell.allocator),
        .size = cell.rand.intRangeAtMost(u8, 1, MaxFoodSize),
        .speed = @floatFromInt(cell.rand.intRangeAtMost(u8, 1, 5)),
    };
}

pub fn deinit(self: *@This()) void {
    for (self.list.items) |item| {
        item.deinit();
    }
    self.list.deinit();
}

pub fn eat(self: *@This(), food: *Food) void {
    if (!self.isFull()) {
        self.list.append(food) catch @panic("Out of memory");
        food.index_block.remove(Food, food);
    }
}

fn isFull(self: *@This()) bool {
    return if (self.list.items.len == self.size) true else false;
}

pub fn drainEnergy(self: *@This(), times: f32) void {
    var energy: f32 = 0;
    for (self.list.items) |item| {
        var _energy = item.energy_efficiency * times;
        if (item.energy < _energy) {
            _energy = item.energy;
        }

        if (item.energy_efficiency >= self.energy_efficiency) {
            const to_drain_energy = self.energy_efficiency * times;
            if (_energy >= to_drain_energy) {
                energy += to_drain_energy;
            } else {
                energy += _energy;
            }
        } else {
            energy += _energy;
        }

        item.energy -= item.energy_efficiency * times;
    }

    for (0..self.list.items.len) |i| {
        const idx: usize = self.list.items.len - i - 1;
        var item = self.list.items[idx];
        if (item.energy <= 0) {
            _ = self.list.swapRemove(idx);
            item.deinit();
        }
    }
}
